package com.dq.service.record.impl;

import com.dq.controller.in.goods.stock.OrgStockCheckMainQuery;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.goods.stock.StockChangeRecord;
import com.dq.domain.org.Org;
import com.dq.domain.record.stockcheck.StockCheckMain;
import com.dq.domain.record.stockcheck.StockCheckRecord;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.exception.customException.AdminException;
import com.dq.repository.BaseRepositories;
import com.dq.repository.record.StockCheckRecordRepository;
import com.dq.service.org.OrgService;
import com.dq.service.record.StockCheckMainService;
import com.dq.service.record.StockCheckRecordService;
import com.dq.service.sys.user.OrgUserService;
import com.dq.vo.Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sound.midi.Soundbank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cf
 */
@Service
public class StockCheckMainServiceImpl extends BaseRepositories implements StockCheckMainService {
    @Autowired
    private OrgService orgService;
    @Autowired
    private StockCheckRecordService stockCheckRecordService;

    @Override
    public List<StockCheckMain> list(OrgStockCheckMainQuery orgStockCheckMainQuery) {
        List<StockCheckMain> stockCheckMainLists = new ArrayList<>();
        //获取角色对应的门店Id;
        Long orgId = orgStockCheckMainQuery.getOrgId();
        //如果是选择全部
        if (0 == orgId) {
            //获取用户管理下的所有门店的信息
            List<Org> listAllByUser = orgService.getListAllByUser();
            for (Org org : listAllByUser) {
                //循环查询角色下的所有门店信息
                orgStockCheckMainQuery.setOrgId(org.getId());
                //构建query
                Map<String, Object> query = createQuery(orgStockCheckMainQuery);
                List<StockCheckMain> stockCheckMainList = dao.find(dao.query2Hql(StockCheckMain.class, query), query);
                stockCheckMainLists.addAll(stockCheckMainList);
            }
            return stockCheckMainLists;
        }


        Map<String, Object> query = createQuery(orgStockCheckMainQuery);
        return dao.find(dao.query2Hql(StockCheckMain.class, query), query);
    }

    @Override
    public Long count(OrgStockCheckMainQuery orgStockCheckMainQuery) {
        Map<String, Object> query = createQuery(orgStockCheckMainQuery);
        return dao.count(dao.count2Hql(StockCheckMain.class, query), query);
    }

    public Map<String, Object> createQuery(OrgStockCheckMainQuery orgStockCheckMainQuery) {
        SysUser loginUser = sysUserService.getUser();

        Map<String, Object> query = orgStockCheckMainQuery.parseMap();

        List<Long> orgidsInList = new ArrayList<>();
        if (orgStockCheckMainQuery.getOrgId() != null) {
            orgidsInList.add(orgStockCheckMainQuery.getOrgId());
        } else {
            // 只显示负责门店信息
            List<Org> orgList = orgService.getListAllByUser();
            for (Org org : orgList) {
                orgidsInList.add(org.getId());
            }
        }
        if (orgidsInList.size() > 0) {
            query.put("org_id" + BaseDaoImpl.inSqlStr, orgidsInList);
            query.remove("orgId");
        }

        if (orgStockCheckMainQuery.getBeginTime() != null) {
            query.put("createTimeMain" + BaseDaoImpl.gteSqlStr, orgStockCheckMainQuery.getBeginTime());
            query.remove("beginTime");
        }
        if (orgStockCheckMainQuery.getEndTime() != null) {
            query.put("createTimeMain" + BaseDaoImpl.lteSqlStr, orgStockCheckMainQuery.getEndTime());
            query.remove("endTime");
        }
        query.put("createUser_id", loginUser.getId());

        return query;
    }


    /**
     * 删除main and info
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        SysUser loginUser = sysUserService.getUserInSection();
        StockCheckMain stockCheckMain = dao.get(StockCheckMain.class, id);
        if (stockCheckMain == null) {
            throw new AdminException("删除ID不存在");
        }

        List<StockCheckRecord> infos = stockCheckRecordRepository.findByDeletedFalseAndStockCheckMain(stockCheckMain);
        for (StockCheckRecord info : infos) {
            info.setDeleted(true);
            info.setUpdateUser(loginUser);
        }

        stockCheckMain.setDeleted(true);
        stockCheckMain.setUpdateUser(loginUser);
        if (infos != null && infos.size() > 0) {
            stockCheckRecordRepository.saveAll(infos);
        }

        stockCheckMainRepository.save(stockCheckMain);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void check(List<Long> orgIds) throws AdminException {
        SysUser loginUser = sysUserService.getUserInSection();
        long createTimeMain = System.currentTimeMillis();

        if (orgIds == null || orgIds.size() <= 0) {
            orgIds = new ArrayList<>();
            // 只显示负责门店信息
            List<Org> orgList = orgService.getListAllByUser();
            for (Org org : orgList) {
                orgIds.add(org.getId());
            }
        }

        List<Map> mapList = new ArrayList<>();
        List<Map> mapList01 = new ArrayList<>();
        for (Long orgId : orgIds) {
            Map<String, Object> stockCheckMain = new HashMap<>(16);
            stockCheckMain.put("id", null);
            stockCheckMain.put("org_id", orgId);
            stockCheckMain.put("create_time_main", createTimeMain);
            stockCheckMain.put("create_time", System.currentTimeMillis());
            stockCheckMain.put("last_modify_time", System.currentTimeMillis());
            stockCheckMain.put("deleted", false);
            stockCheckMain.put("version", 1);
            stockCheckMain.put("create_user_id", loginUser.getSection().getId());
            stockCheckMain.put("update_user_id", loginUser.getSection().getId());

            Map<String, Object> columnMap = new HashMap<>(16);
            columnMap.put("columnMap", stockCheckMain);
            int judgeNum = stockCheckMainMapper.insertObject(columnMap);
            if (judgeNum > 0) {
                getRecord(loginUser, mapList01, orgId, Long.parseLong(stockCheckMain.get("id").toString()));
            }

            mapList.add(stockCheckMain);
        }

//        if(mapList.size() > 0) {
//            Map<String, Object> columnMap = new HashMap<>(16);
//            columnMap.put("columnList", mapList);
//            columnMap.put("id", null);
//            int judgeNum = stockCheckMainMapper.insertObjectList(columnMap);
//            if(judgeNum > 0) {
//                for (Map map : mapList) {
//                    getRecord(loginUser, mapList01, Long.parseLong(map.get("org_id").toString()), Long.parseLong(map.get("id").toString()));
//                }
//            }
//        }

        if (mapList01.size() > 0) {
            Map<String, Object> columnMap = new HashMap<>(16);
            columnMap.put("columnList", mapList01);
            stockCheckRecordMapper.insertObjectList(columnMap);
        }

    }

    private void getRecord(SysUser loginUser, List<Map> mapList01, Long orgId, long mainId) {
        List<Map<String, Object>> maps = stockCheckRecordService.selectCheck(orgId);
        for (Map<String, Object> map : maps) {
            Map<String, Object> stockCheckRecord = new HashMap<>(16);
            stockCheckRecord.put("id", null);
            stockCheckRecord.put("stock_check_main_id", mainId);
            stockCheckRecord.put("goods_id", map.get("goods_id"));
            stockCheckRecord.put("product_id", map.get("product_id"));
            stockCheckRecord.put("org_id", orgId);
            stockCheckRecord.put("addall", map.get("addall"));
            stockCheckRecord.put("reduceloss", map.get("reduceloss"));
            stockCheckRecord.put("reducesell", map.get("reducesell"));
            stockCheckRecord.put("residuestock", map.get("residuestock"));
            stockCheckRecord.put("create_time", System.currentTimeMillis());
            stockCheckRecord.put("last_modify_time", System.currentTimeMillis());
            stockCheckRecord.put("deleted", false);
            stockCheckRecord.put("version", 1);
            stockCheckRecord.put("create_user_id", loginUser.getSection().getId());
            stockCheckRecord.put("update_user_id", loginUser.getSection().getId());

            mapList01.add(stockCheckRecord);
        }
    }

}
